package com.szsh.aiot.framework.influxdb;

import com.szsh.aiot.hsm.domain.camera.AbnormalLogin;
import com.szsh.aiot.hsm.utils.Hash163;
import org.influxdb.dto.Query;
import org.influxdb.impl.InfluxDBMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class AbnormalLoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbnormalLoginService.class);

    @Autowired
    private Hash163 hash;
    @Autowired
    private InfluxDBMapper influxMapper;

    /**
     * 查询vality天内的异常登录信息
     *
     * @param phone
     * @param vality
     * @return
     */
    public List<AbnormalLogin> getAbnormalLogin(String phone, int vality) {
        StringBuilder querySB = new StringBuilder();
        querySB.append("select * from abnormal_login where hashPhone='").append(hash.sHash(phone))
                .append("' and phone='").append(phone).append("'");
        querySB.append(" and time>now()-").append(vality)
                .append("d order by time desc tz('Asia/Shanghai')");
        LOGGER.info("abnormal influxDB query:{}", querySB.toString());
        Query query = new Query(querySB.toString());
        return influxMapper.query(query, AbnormalLogin.class);
    }

    /**
     * 查询指定时间内的异常登录信息
     *
     * @param phone
     * @param
     * @param startTime
     * @param endTime
     * @return
     */
    public List<AbnormalLogin> getListByTime(String phone, String startTime, String endTime) {
        StringBuilder querySB = new StringBuilder();
        querySB.append("select * from abnormal_login where hashPhone='").append(hash.sHash(phone));
        querySB.append("' and phone='").append(phone).append("'");
        querySB.append(" and time>='").append(startTime).append("' and time<='").append(endTime);
        querySB.append("' tz('Asia/Shanghai')");
        LOGGER.info("login influxDB query:{}", querySB.toString());
        Query query = new Query(querySB.toString());
        return influxMapper.query(query, AbnormalLogin.class);
    }
}
